package com.vone.export.until;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {
	public static List<List<String>> readExcel(File file, String fileName) {
		List<List<String>> list = null;
		try {
			// 获得Workbook工作薄对象
			Workbook workbook = getWorkBook(file, fileName);
			// 创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
			list = new ArrayList<List<String>>();
			if (workbook != null) {
				// 获得当前sheet工作表
				Sheet sheet = workbook.getSheetAt(0);
				if (sheet == null) {
					return list;
				}
				// 获得当前sheet的开始行
				int firstRowNum = sheet.getFirstRowNum();
				// 获得当前sheet的结束行
				int lastRowNum = sheet.getLastRowNum();
				// 循环除了第一行的所有行
				for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
					// 获得当前行
					Row row = sheet.getRow(rowNum);
					if (row == null) {
						continue;
					}
					// 获得当前行的开始列
					int firstCellNum = row.getFirstCellNum();
					// 获得当前行的列数
					int lastCellNum = row.getPhysicalNumberOfCells();
					List<String> cells = new ArrayList<String>();
					// 循环当前行
					for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
						Cell cell = row.getCell(cellNum);
						cells.add(getCellValue(cell));
					}
					list.add(cells);

				}

				workbook.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			list = null;
		}
		return list;
	}

	public static Workbook getWorkBook(File file, String fileName) {
		// 创建Workbook工作薄对象，表示整个excel
		Workbook workbook = null;
		try {
			// 获取excel文件的io流
			InputStream is = new FileInputStream(file);
			// 根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
			if (fileName.endsWith("xls")) {
				// 2003
				workbook = new HSSFWorkbook(is);
			} else if (fileName.endsWith("xlsx")) {
				// 2007
				workbook = new XSSFWorkbook(is);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return workbook;
	}

	@SuppressWarnings("deprecation")
	public static String getCellValue(Cell cell) {
		String cellValue = "";
		if (cell == null) {
			return cellValue;
		}
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		int cellType = cell.getCellType();
		switch (cellType) {
		case HSSFCell.CELL_TYPE_STRING: // 文本
			cellValue = cell.getStringCellValue();
			break;
		case HSSFCell.CELL_TYPE_NUMERIC: // 数字、日期
			if (DateUtil.isCellDateFormatted(cell)) {
				cellValue = fmt.format(cell.getDateCellValue()); // 日期型
			} else {
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cellValue = cell.getStringCellValue();
			}
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN: // 布尔型
			cellValue = String.valueOf(cell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK: // 空白
			cellValue = cell.getStringCellValue();
			break;
		default:
			cellValue = "";
		}
		return cellValue;
	}

	public static InputStream buildExcel(List<ExcelHeader> headers, List<?> list) throws Exception {
		return buildExcel(null, headers, list);
	}

	public static InputStream buildExcel(String title, List<ExcelHeader> headers, List<?> list) throws Exception {

		// 创建HSSFWorkbook对象
		HSSFWorkbook wb = new HSSFWorkbook();
		// 创建HSSFSheet对象
		HSSFSheet sheet = wb.createSheet("sheet1");
		HSSFRow row = null;
		int index = 0;

		// 生成标题
		if (title != null) {
			row = sheet.createRow(index);
			CellRangeAddress cra = new CellRangeAddress(0, 0, 0, headers.size() - 1);
			sheet.addMergedRegion(cra);
			HSSFCell cell = row.createCell(0);
			// 设置单元格的值
			cell.setCellValue(title);
			HSSFCellStyle cellStyle = wb.createCellStyle(); // 新建单元格样式
			cellStyle.setAlignment(HorizontalAlignment.CENTER);
			cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
			cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
			cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
			cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
			HSSFFont fontHead = wb.createFont();
			fontHead.setBold(true);
			fontHead.setFontName("宋体");
			fontHead.setFontHeightInPoints((short) 18);
			cellStyle.setFont(fontHead);
			cell.setCellStyle(cellStyle);
			index++;
		}

		// 生成表头
		row = sheet.createRow(index);
		index++;
		for (int i = 0; i < headers.size(); i++) {
			ExcelHeader header = headers.get(i);
			// 创建HSSFCell对象
			HSSFCell cell = row.createCell(i);
			// 设置单元格的值
			cell.setCellValue(header.getName());
			HSSFCellStyle cellStyle = wb.createCellStyle(); // 新建单元格样式
			if (header.isAlignmentCenter()) {
				cellStyle.setAlignment(HorizontalAlignment.CENTER);
			}
			if (header.isBorder()) {
				cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
				cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
				cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
				cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
			}
			HSSFFont fontHead = wb.createFont();
			fontHead.setBold(header.isHeaderBold());
			fontHead.setFontName(header.getFontName());
			fontHead.setFontHeightInPoints(header.getHeaderFontSize());
			if (header.getHeaderColor() != null) {
				fontHead.setColor(header.getHeaderColor().getIndex());
			}
			cellStyle.setFont(fontHead);
			cell.setCellStyle(cellStyle);
			sheet.setColumnWidth(i, header.getWidth());
		}
		// 生成数据行
		for (int k = 0; k < list.size(); k++) {
			row = sheet.createRow(index);
			index++;
			for (int i = 0; i < headers.size(); i++) {
				ExcelHeader header = headers.get(i);
				// 创建HSSFCell对象
				HSSFCell cell = row.createCell(i);
				// 设置单元格的值
				setCellValue(cell, list.get(k), header.getField());
				HSSFCellStyle cellStyle = wb.createCellStyle(); // 新建单元格样式
				if (header.isAlignmentCenter()) {
					cellStyle.setAlignment(HorizontalAlignment.CENTER);
				}
				if (header.isBorder()) {
					cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
					cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
					cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
					cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
				}
				HSSFFont font = wb.createFont();
				// font.setBold(header.isHeaderBold());
				font.setFontName(header.getFontName());
				font.setFontHeightInPoints(header.getFontSize());
				if (header.getTextColor() != null) {
					font.setColor(header.getTextColor().getIndex());
				}
				cellStyle.setFont(font);
				cell.setCellStyle(cellStyle);
			}
		}

		// 输出Excel文件
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		wb.write(os);
		byte[] fileContent = os.toByteArray();
		ByteArrayInputStream is = new ByteArrayInputStream(fileContent);
		os.close();
		wb.close();
		return is;

	}

	public static void setCellValue(Cell cell, Object obj, String field) {
		String methodName = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
		try {
			Method getterMethod = obj.getClass().getMethod(methodName);
			Object value = getterMethod.invoke(obj);
			if (value != null) {
				cell.setCellValue(value.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
